package com.myblog.web.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myblog.Mapper.Tagmapper;
import com.myblog.po.Tag;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Parameter;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class TagController {

    @Autowired
    private Tagmapper tagmap;


    @GetMapping("/tags")
    public String types( @RequestParam(value="page",required = false) Integer page
    , Model model){
        if (page == null){
            page = 1;
        }

        PageHelper.startPage(page,4);
        List<Tag> tags = tagmap.listTag();
        PageInfo pageInfo = new PageInfo(tags);

        model.addAttribute("page",pageInfo);
        return "admin/tags";
    }

    /*转到编辑页*/
    @GetMapping("/tags/input")
    public String input(Model model){

        model.addAttribute("type",new Tag());

        return "admin/tags-input";
    }


    /*保存相应信息转到编辑页*/
    @GetMapping("/tags/{id}/input")
    public String editInput(@PathVariable Long id, Model model)
    {

        model.addAttribute("type",tagmap.getTag(id));
        return "/admin/tags-input";

    }


/*保存信息*/
    @PostMapping("/tags")
    public String post(@RequestParam("id") Long id,@RequestParam("name") String name,Model model)
    {
            Tag t1 = tagmap.getTagByName(name);

            if(t1!=null){
                model.addAttribute("messageerro","不可以重复");
                return "/admin/tags-input";

            }
        if(name == null)
        {
            model.addAttribute("messageerro","名字不为空");
            return "/admin/tags-input";
        }

        Tag t = new Tag();
        t.setName(name);
        t.setId(id);
          tagmap.saveTag(t);
           return "redirect:/admin/tags";
    }

/*编辑信息*/
    @PostMapping("/tags/{id}")
    public String editpost(@RequestParam("id") Long id,@RequestParam("name") String name,Model model)
    {
        Tag t1 = tagmap.getTagByName(name);

        if(name == null)
        {
            model.addAttribute("messageerro","名字不为空");
            return "/admin/tags-input";
        }

        Tag t = new Tag();
        t.setName(name);
        t.setId(id);
        tagmap.updateTag(t);
        return "redirect:/admin/tags";
    }


    /*删除*/
    @GetMapping("/tags/{id}/delete")
    public String delete(@PathVariable Long id)
    {
        tagmap.deleteTag(id);
        return "redirect:/admin/tags";


    }



}


